var $currentThis;
var currentLevel = {};//当前部门层级,包括层级编号及层级名称

function initTree(callback, successCallback, failCallback) {
    getTreeData("0", function (data) {
        // var data = getTreeData("0");
        if (data.length > 0) {
            $(".tree").append(makeTree(data));
            activeTree(callback);
            successCallback.call();
        } else {
            failCallback.call();
        }
    })
}
function makeTree(data) {
//    先判断数据长度，如果数据长度大于等于1，证明当前点击的数据有子数据，要生成默认fold类li
    if (data.length >= 1) {
        var $divContent = $("<div class='foldContent'></div>");
        var $ul = $('<ul class="level"></ul>');
        for (var i = 0; i < data.length; i++) {
            var $li = $("<li class='fold'></li>");
            var $a = $("<a></a>").data("index", data[i].id);
            $a.text(data[i].name);
            $li.append($a);
            $ul.append($li);
        }
        $divContent.append($ul);
        return $divContent;
    } else {
    //    否则说明没有子数据，直接返回
        return null;
    }
}
function getTreeData(index, callback) {
    var resultData = [];
    $.ajax({
        type: 'POST',
        url: mmssm_url + 'department/level',
        // async: false,
        dataType: 'json',
        data: 'level=' + index,
    }).done(function (data) {
        callback.call(this, data);
        // resultData = data;
    }).fail(function () {
        console.log("Error!");
    });
    return resultData;
}

//获取当前的层级信息数组:包括{全层级，父层级，当前部门id}
function getCurrentLevel() {
    var level = {};
    if (currentLevel.fullLevel) {
        var fullLevel = currentLevel.fullLevel;
        var levelArray = fullLevel.split(".");
        var currentId = levelArray.splice(levelArray.length - 1, 1);
        level.fullLevel = currentLevel.fullLevel;
        level.parentLevel = levelArray.join('.');
        level.currentId = currentId.join('.');
        level.parentId = levelArray.slice(-1).join('.');
        level.fullName = currentLevel.fullName;
        return level;
    } else {
        return null;
    }
}

//下面的方法负责绑定tree的点击事件
function activeTree(callback) {
    //，每次绑定事件之前，先清除所有事件，防止多次绑定重复的事件
    $(".tree *").off();
    $('.tree li.fold a').click(function () {
        //当前点击项的完整层级
        var fullName = $(this).text();//机构全路径名
        var fullLevel = $(this).data("index");
        var temp = '';
        var temp2 = '';
        var level = $(this).parents('.foldContent').siblings('a');
        level.each(function () {
            temp = temp + $(this).data("index") + '.';
            temp2 = temp2 + $(this).text() + '-';
        });
        fullName = temp2 + fullName;
        fullLevel = "0." + temp + fullLevel;
        currentLevel.fullLevel = fullLevel;
        currentLevel.fullName = fullName;
        // 先判断是否已经加载过一次，如果是则不再请求数据
        if ($(this).siblings(".foldContent").length <= 0) {
            $currentThis = $(this);
            getTreeData(fullLevel, function (data) {
                //如果没有获取到数据，则证明当前li没有子数据，是unfold类型
                //改成unfold类型
                if (data.length == 0) {
                    $currentThis.parent().removeClass("fold").addClass("unfold");
                } else {
                    $currentThis.parent().append(makeTree(data));
                }
                activeTree(callback);
            });
        }
        if ($(this).parent().hasClass('active')) {
            // 找到当前点击的li的class，通过class判断li是否被展开
            //    li已经展开，本次点击将会关闭当前li
            $(this).parent().removeClass('active');
       } else {
           //    li未展开，本次点击将展开当前li
           $(this).parent().addClass('active');
       }
        callback.call();
    });
    $('.tree li.unfold a').click(function () {//不可展开的li点击事件
        //当前点击项的完整层级
        var fullName = $(this).text();//机构全路径名
        var fullLevel = $(this).data("index");
        var temp = '';
        var temp2 = '';
        var level = $(this).parents('.foldContent').siblings('a');
        level.each(function () {
            temp = temp + $(this).data("index") + '.';
            temp2 = temp2 + $(this).text() + '-';
        });
        fullName = temp2 + fullName;
        fullLevel = "0." + temp + fullLevel;
        currentLevel.fullLevel = fullLevel;
        currentLevel.fullName = fullName;
        callback.call();
    });

}

function deleteDep(callback, successCallback, failCallback) {
    var level = getCurrentLevel();
    if (level) {
        $.ajax({
            type: "POST",
            url: mmssm_url + "department/delete",
            dataType: "JSON",
            data: {
                id: getCurrentLevel().currentId
            },
        }).done(function () {
            $(".tree *").remove();
            initTree(callback, successCallback, failCallback);
        }).fail(function () {
            console.log("Delete ajax failed!");
            failCallback.call();
        });
    } else {
        alert("None development selected.");
        failCallback.call();
    }
}
function insertDep(department, callback, failCallback, successCallback) {
    $.ajax({
        type: "POST",
        url: mmssm_url + "department/insert",
        dataType: "JSON",
        data: {
            name: department.name,
            comment: department.comment,
            level: department.level.fullLevel,
            parentId: department.level.currentId,
            isDep: department.isDep
        },
    }).done(function () {
        $(".tree *").remove();
        initTree(callback, successCallback, failCallback);
    }).fail(function () {
        console.log("Insert ajax failed!");
        failCallback.call();
    });
}

function updateDep(department, initCallback, successCallback, failCallback) {
    debugger;
    $.ajax({
        type: "POST",
        url: mmssm_url + "department/update",
        dataType: "JSON",
        data: {
            id: department.level.currentId,
            name: department.name,
            comment: department.comment,
            isDep: department.isDep
        },
    }).done(function () {
        $(".tree *").remove();
        initTree(initCallback, successCallback, failCallback);
    }).fail(function () {
        console.log("Insert ajax failed!");
        failCallback.call();
    });
}
